import { Message } from '@/plugins/element'
import { response } from '@/ts/type'
import { AxiosResponse } from 'axios'
import NProgress from 'nprogress'

export const dealResponseError = (error: any): Promise<response<any>> => {
  let message
  // 这里用来处理http常见错误，进行全局提示
  switch (error.response.status) {
  case 400:
    message = '请求错误(400)'
    break
  case 401:
    message = '未授权，请重新登录(401)'
    // 这里可以做清空storage并跳转到登录页的操作
    break
  case 403:
    message = '拒绝访问(403)'
    break
  case 404:
    message = '请求出错(404)'
    break
  case 408:
    message = '请求超时(408)'
    break
  case 500:
    message = '服务器错误(500)'
    console.log('500')
    location.href = '#/500'
    break
  case 501:
    message = '服务未实现(501)'
    break
  case 502:
    message = '网络错误(502)'
    break
  case 503:
    message = '服务不可用(503)'
    break
  case 504:
    message = '网络超时(504)'
    break
  case 505:
    message = 'HTTP版本不受支持(505)'
    break
  default:
    message = `连接出错(${error.response.status})!`
  }
  Message.error(message)
  NProgress.done()
  return Promise.reject(error.response)
}
// FIXME 2023-4-12 21:30:回应拦截后会出线promise的catch
// TODO 2023-4-13 19:11:拦截优化，使返回的数据响应的回复多样化
export const dealResponse = (res: AxiosResponse<response<any>>) => {
  // eslint-disable-next-line prefer-const
  let { code, message, data } = res.data
  try {
    switch (code) {
    case 4001:
      location.href = '#/Login'
      localStorage.clear()
      Message.error(message)
      break
    case 200:
      return { message, data }
    case 2000:
      return data
    case 2006:
      return message
    default:
      return Message.error(message)
    }
  } finally {
    NProgress.done()
  }
}
